node {
    //bakArtifact("/home/tomcat/webapps","/opt/app-bak")
    //rollBackForWar('/home/tomcat/webapps','/opt/app-bak')
    //printParams()
    //testPassword()
    testSsh('1b4757e9-0cd6-44db-bbdc-e627d58a98e9');
}

def testSsh(cret){
    stage('SSH TEST'){
        sshagent (credentials: [cret]) {
            sh 'ssh -o StrictHostKeyChecking=no -l yh 192.168.3.8 uname -a'
        }
    }
}

def testPassword(){
    wrap([$class: 'MaskPasswordsBuildWrapper', varPasswordPairs: [[password: "${params.mypwd}", var: 'PASSWORD']]]) {
        println params.mypwd
        sh """
          echo Hello World ${params.mypwd}
          """
    }
}

def printParams() {
    sh 'env > env.txt'
    readFile('env.txt').split("\r?\n").each {
        println it
    }
}

def bakArtifact(tomcatWebPath,bakPath){
    try {
        stage('Bak Artifact') {
            echo "Bak Artifact"
            sh "ls ${tomcatWebPath} | grep war > bakResult"
            def bakResult = readFile('bakResult').split("\r?\n")
            sh "mkdir -p ${bakPath}"
            bakResult.each {
                sh """
                   cp /home/tomcat/webapps/${it} /opt/app-bak
                 """
            }
            sh "ls ${bakPath}"
        }
    }catch (e){
        echo 'BakArtifact Error !'
        throw e
    }
}


def rollBackForWar(tomcatWebPath,bakPath){
    try{
        stage('Stop Tomcat'){
            stopApp('tomcat')
        }
        stage('RollBack Artifact') {
            sh """
               cp ${bakPath}/*.war ${tomcatWebPath}
             """
            sh "ls ${tomcatWebPath}"
        }
        stage('Start Tomcat'){
            startTomcat('/home/tomcat')
        }
    }catch (e){
        echo 'RollBackForWar Error !'
        throw e
    }
}

def stopApp(instanceName){
    println("---- stop App ----:"+instanceName)
    def res = sh(script: 'ps -ef | grep -w ${instanceName} | grep -v grep | wc -l', returnStdout: true).trim()
    echo res
    if(res == '1'){
        def pid = sh(script: 'ps -ef | grep -w ${instanceName} | grep -v grep | awk \'{print $2}\'',returnStdout: true).trim()
        echo 'Tomcat pid: '+ pid
        sh "kill ${pid}"
    }
}

def startTomcat(tomcatHome){
    println("---- startTomcat ----:"+tomcatHome)
    script{
        withEnv(['JENKINS_NODE_COOKIE=dontkillme']) {
            sh """
            ${tomcatHome}/bin/startup.sh
          """
        }
    }
}